<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <meta name="Generator" content="xnr®">
  <meta name="Author" content="小男人-923227829@qq.com">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <title>角色管理</title>
  <link rel="stylesheet" href="../inc/layui/css/layui.css">
  <link rel="stylesheet" href="../css/comm.css">
  <style>
    .layui-border-box {
      height: auto !important;
    }
  </style>
</head>

<body class="layui-layout-body">
  <header>
    <div class="layui-form" id="search-form">
    </div>
  </header>
  <table class="layui-hide" id="table" lay-filter="table"></table>
</body>
<script type="text/html" id="formTpl">
  <div id="form" class="layui-form" style="margin:20px 20px 0px 20px;">
    <input type="hidden" value="{{d.roleId?d.roleId:''}}" name="roleId" />
    <div class="layui-form-item">
      <label class="layui-form-label">角色名称</label>
      <div class="layui-input-block">
        <input value="{{d.name?d.name:''}}" type="text" name="name" lay-verify="required" id="name" autocomplete="off"
          placeholder="请输入角色的名称" class="layui-input" />
      </div>
    </div>
    <div class="center">
      <button class="layui-btn" lay-submit="" lay-filter="sub">保存</button>
      <button class="layui-btn layui-btn-primary" id="closeform">关闭</button>
    </div>
  </div>
</script>
<script type="text/html" id="authorTpl">
  <div id="form1" class="layui-form" style="margin-top: 20px;margin-right:30px;">
    <input type="hidden" value="{{d.roleId?d.roleId:''}}" name="roleId" />
    <div class="layui-form-item">
      <label class="layui-form-label">选择菜单</label>
      <div class="layui-input-block">
        <table class="layui-hidden" id="treeTable" lay-filter="treeTable"></table>
      </div>
    </div>
    <div class="center">
      <button class="layui-btn" lay-submit="" lay-filter="sub">保存</button>
      <button class="layui-btn layui-btn-primary" id="closeform">关闭</button>
    </div>
  </div>
</script>
<script type="text/html" id="barDemo">
  <a class="layui-btn layui-btn-xs" lay-event="edit">编辑权限</a>
</script>
<script type="text/html" id="barbtnDemo">
  {{# if(d.pid > 0){ }}
  <a class="layui-btn layui-btn-xs" lay-event="edit">编辑按钮权限</a> {{# } }}
</script>
<script type="text/html" id="statusType">
  {{# if(d.status == 1){ }}
  <span style='color: #09b825'>已启用</span> {{# }else{ }}
  <span style='color: #aa1111'>已禁用</span> {{# } }}
</script>
<script type="text/html" id="btnTpl">
  <div id="form" class="layui-form" style="margin: 20px;">
    <div id="btntransfer" class="demo-transfer"></div>
    <div class="center" style="margin-top:20px;">
      <button class="layui-btn" lay-submit="" lay-filter="sub">保存</button>
      <button class="layui-btn layui-btn-primary" id="closeform">关闭</button>
    </div>
  </div>
</script>

<script type="text/javascript" src="../inc/layui/layui.js"></script>
<script type="text/javascript" src="../inc/g.js"></script>
<script type="text/javascript" src="../inc/layui/lay/treeGrid.js"></script>
<script type="text/javascript">
  layui.extend({
    treeGrid: '../../inc/layui/lay/treeGrid'
  })

  var data = [];

  //加载页面
  function pageload() {
    layui.use(['tree', 'treeGrid', 'transfer', 'util'], function () {
      Comm.treeGrid = layui.treeGrid;
      Comm.transfer = layui.transfer;
    });
    //初始化列表
    Comm.table.render({
      elem: '#table',
      url: config.root + '/admin/role/query', //列表请求接口
      where: { //接口参数
      },
      cols: [
        [{
          checkbox: true
        }, {
          field: 'name',
          title: '角色名称'
        /*}, {
          field: 'menuIds',
          title: '菜单id',
          hide: true*/
        }, {
          field: 'status',
          title: '状态',
          templet: '#statusType'
        }]
      ],
      done: function (d, curr, count) {},
      id: 'table',
      page: false, //是否分页
    });

    //监听table列表里按钮点击事件
    Comm.table.on('tool(table)', function (obj) {
      if (obj.event == 'edit') {
        opendialog(obj.data);
      }
    });

    AJAX.GET('/admin/menu/button/list?', function (d) {
      if (d.code == 1) {
        Comm.buttonList = d.data
      }
    })

  }

  //新增
  function add(d) {
    d = d == undefined ? {} : d;
    Comm.laytpl($("#formTpl").html()).render(d, function (html) {
      layer.open({
        type: 1,
        title: '新增',
        area: ['450px', '180px'],
        maxmin: true,
        content: html,
        success: function (layero) {
          //验证必填项
          Comm.form.verify();
          //提交表单
          Comm.form.on('submit(sub)', function (data) {
            AJAX.POST('/admin/role/add', data.field, function (d) {
              if (d.code == 1) {
                layer.closeAll();
                layer.msg("保存成功!", {
                  icon: 1
                });
                //执行重载
                Comm.table.reload('table');
              } else {
                layer.msg("保存失败!", {
                  icon: 5
                })
              }
            })
          });
          $("#closeform").click(function () {
            layer.closeAll();
          })
        }
      });
    })

  }

  //编辑权限
  function updateAuth() {
    var d = Comm.table.checkStatus('table'); //获取选中的数据
    if (d.data.length != 1) {
      Comm.msg("请选择一条数据", 5)
      return;
    }
    opendialog(d.data[0])
  }

  //编辑
  function update() {
    var d = Comm.table.checkStatus('table'); //获取选中的数据
    if (d.data.length != 1) {
      Comm.msg("请选择一条数据", 5)
      return;
    }
    d = d.data[0];
    Comm.laytpl($("#formTpl").html()).render(d, function (html) {
      layer.open({
        type: 1,
        title: '编辑',
        area: ['450px', '180px'],
        maxmin: true,
        content: html,
        success: function (layero) {
          //验证必填项
          Comm.form.verify();
          //提交表单
          Comm.form.on('submit(sub)', function (data) {
            AJAX.POST('/admin/role/update', data.field, function (d) {
              if (d.code == 1) {
                layer.closeAll();
                layer.msg("保存成功!", {
                  icon: 1
                });
                //执行重载
                Comm.table.reload('table');
              } else {
                layer.msg("保存失败!", {
                  icon: 5
                })
              }
            })
          });
          $("#closeform").click(function () {
            layer.closeAll();
          })
        }
      });
    });
  }

  //删除
  function del() {
    var d = Comm.table.checkStatus('table'); //获取选中的数据
    if (d.data.length != 1) {
      Comm.msg("请选择一条数据", 5)
      return;
    }
    d = d.data[0];

    Comm.confirm('确定选择删除数据', function () {
      AJAX.POST('/admin/role/delete', {
        roleId: d.roleId
      }, function (d) {
        if (d.code == 1) {
          layer.msg("删除成功!", {
            icon: 1
          });
          //执行重载
          reference();
        } else {
          layer.msg("删除失败!", {
            icon: 5
          })
        }
      })
    })
  }

  //启用
  function enable() {
    var d = Comm.table.checkStatus('table'); //获取选中的数据
    if (d.data.length != 1) {
      Comm.msg("请选择一条数据", 5)
      return;
    }
    d = d.data[0];
    if (d.status == 1) {
      Comm.msg("该角色已启用", 5)
      return
    }

    Comm.confirm('确定选择启用角色', function () {
      AJAX.POST('/admin/role/setEnable', {
        roleId: d.roleId,
        enable: 1,
      }, function (d) {
        if (d.code == 1) {
          layer.msg("启用成功!", {
            icon: 1
          });
          //执行重载
          reference();
        } else {
          layer.msg("启用失败!", {
            icon: 5
          })
        }
      })
    })
  }

  //禁用
  function disable() {
    var d = Comm.table.checkStatus('table'); //获取选中的数据
    if (d.data.length != 1) {
      Comm.msg("请选择一条数据", 5)
      return;
    }
    d = d.data[0];
    if (d.status == 0) {
      Comm.msg("该角色已禁用", 5)
      return
    }

    Comm.confirm('确定选择禁用角色', function () {
      AJAX.POST('/admin/role/setEnable', {
        roleId: d.roleId,
        enable: 0,
      }, function (d) {
        if (d.code == 1) {
          layer.msg("禁用成功!", {
            icon: 1
          });
          //执行重载
          reference();
        } else {
          layer.msg("禁用失败!", {
            icon: 5
          })
        }
      })
    })
  }

  //刷新
  function reference() {
    Comm.table.reload('table');
  }

  //处理权限
  function opendialog(data) {
    Comm.roledata = data;
    //查询权限
    AJAX.GET('/admin/menu/myList?force=1&roleId=' + Comm.roledata.roleId, function (d) {
      if (d.code == 1) {
        if(null != d.data){
        Comm.myList = d.data;
        }else{
          Comm.myList = [];
        }
        Comm.laytpl($("#authorTpl").html()).render(Comm.roledata, function (html) {
          layer.open({
            type: 1,
            title: '编辑权限',
            area: ['700px', '600px'],
            maxmin: true,
            content: html,
            success: function (layero) {
              tree();
              $("#closeform").click(function () {
                layer.closeAll();
              });
              //验证必填项
              Comm.form.verify();
              //提交表单
              Comm.form.on('submit(sub)', function (data) {
                var result1 = [];
                var result2 = [];
                var d = Comm.treeGrid.checkStatus('treeTable'); //获取选中的数据
                if (d.data.length > 0) {
                  for (var i = 0; i < d.data.length; i++) {
                    if (d.data[i].leve == 2 || d.data[i].leve == 1)
                      result1.push(d.data[i])
                    if (d.data[i].leve == 3)
                      result2.push(d.data[i])
                  }
                }
                if (result1.length <= 0) {
                  layer.msg("请选择菜单!", {
                    icon: 5
                  })
                  return;
                }

                var jsonData = []
                for (var i = 0; i < result1.length; i++) {
                  var btnIds = []
                  if (result1[i].leve == 2) {
                    for (var j = 0; j < result2.length; j++) {
                      if (result1[i].menuId == result2[j].pid) {
                        btnIds.push(result2[j].menuId.split('_')[1]);
                      }
                    }
                  }
                  var e = {
                    menuId: result1[i].menuId,
                    btnIds: btnIds.join(',')
                  }
                  jsonData.push(e);
                }

                data.field.roleId = Comm.roledata.roleId;
                data.field.jsonData = JSON.stringify(jsonData);

                AJAX.POST('/admin/role/updateMenu', data.field, function (d) {
                  if (d.code == 1) {
                    layer.closeAll();
                    layer.msg("保存成功!", {
                      icon: 1
                    });
                    //执行重载
                    Comm.table.reload('table');
                  } else {
                    layer.msg("保存失败!", {
                      icon: 5
                    })
                  }
                })
              });
            }
          });
        })

      }
    })

    function tree() {
      Comm.treeGrid.render({
        id: 'treeTable',
        elem: '#treeTable',
        url: '/admin/menu/list',
        where: {
          force: 1
        },
        idField: 'menuId', //必須字段
        treeId: 'menuId', //树形id字段名称
        treeUpId: 'pid', //树形父id字段名称
        treeShowName: 'menuName', //以树形式显示的字段
        heightRemove: [".dHead", 350], //不计算的高度,表格设定的是固定高度，此项不生效
        isFilter: false,
        iconOpen: true, //是否显示图标【默认显示】
        isOpenDefault: true, //节点默认是展开还是折叠【默认展开】
        loading: true,
        method: 'get',
        cols: [
          [{
            type: 'checkbox',
            field: 'menuId',
            width: 80,
            align: 'center',
            sort: true
          }, {
            field: 'menuName',
            title: '菜单名称'
          }]
        ],
        isPage: false,
        parseData: function (res) {
          if (null == res) {
            return [];
          }
          var tempData = [];
          for (var i = 0; i < res.data.length; i++) {
            var e = res.data[i];
            if (e.pid == 0) {
              e.leve = 1;
            } else {
              e.leve = 2;
            }
            for (var j = 0; j < Comm.myList.length; j++) {
              if (Comm.myList[j].menuId == e.menuId) {
                e.lay_is_checked = true;
                if (null != Comm.myList[j].btnId) {
                  e.tts = Comm.myList[j].btnId.split(',');
                } else {
                  e.tts = [];
                }
              }
            }

            tempData.push(e);
            if (res.data[i].pid >= 0) {
              for (var j = 0; j < Comm.buttonList.length; j++) {
                var btnIds;
                if (null != e.btnIds) {
                  btnIds = e.btnIds.split(',');
                } else {
                  btnIds = [];
                }
                if (btnIds && btnIds.length > 0) {
                  if (btnIds.indexOf(Comm.buttonList[j].btnId + "") >= 0) {
                    var ee = {
                      "menuId": e.menuId + "_" + Comm.buttonList[j].btnId,
                      "menuName": Comm.buttonList[j].btnName,
                      "pid": e.menuId,
                      "leve": 3,
                    };
                    if (e.tts && e.tts.indexOf(Comm.buttonList[j].btnId + "") >= 0) {
                      ee.lay_is_checked = true;
                    }
                    tempData.push(ee);
                  }
                }
              }
            }
          }
          res.data = tempData;
          data = res.data;
          return res;
        },
        // height: 550, //计算table底部距离
      });

      Comm.treeGrid.on('tool(treeTable)', function (obj) {
        if (obj.event == 'edit') {
          Comm.objdata = obj.data;
          Comm.laytpl($("#btnTpl").html()).render(obj.data, function (html) {
            layer.open({
              type: 1,
              title: '编辑按钮权限',
              area: ['580px', '510px'],
              maxmin: true,
              content: html,
              success: function () {
                var btnlist = []
                for (var i = 0; i < Comm.buttonList.length; i++) {
                  if (Comm.objdata.btnId && Comm.objdata.btnId.split(',').indexOf(Comm.buttonList[i]
                      .btnId + "") >= 0) {
                    btnlist.push(Comm.buttonList[i])
                  }
                }

                Comm.transfer.render({
                  id: 'btntransfer',
                  elem: '#btntransfer',
                  data: btnlist,
                  parseData: function (res) {
                    return {
                      "value": res.btnId, //数据值
                      "title": res.btnName, //数据标题
                      "disabled": res.disabled, //是否禁用
                      "checked": res.checked, //是否选中
                    }
                  },
                  value: []
                });
                //提交表单
                Comm.form.on('submit(sub)', function (data) {
                  data.field.roleId = Comm.roledata.roleId;
                  data.field.menuId = Comm.objdata.menuId;
                  data.field.btnIds = [];

                  var getBtnData = Comm.transfer.getData('btntransfer'); //获取右侧数据
                  if (getBtnData && getBtnData.length > 0) {
                    for (var i = 0; i < getBtnData.length; i++) {
                      data.field.btnIds.push(getBtnData[i].value)
                    }
                  }
                  data.field.btnIds.join(',');
                  AJAX.POST('/admin/role/updateMenu', data.field, function (d) {
                    if (d.code == 1) {
                      layer.closeAll();
                      layer.msg("保存成功!", {
                        icon: 1
                      });
                    } else {
                      layer.msg("保存失败!", {
                        icon: 5
                      })
                    }
                  })
                });
              }
            });
          })

        }
      });

      Comm.treeGrid.on("checkbox(treeTable)", function (obj) {
        var d = Comm.treeGrid.getDataList('treeTable');

        // data[100].lay_is_checked = true,
        var checked = obj.data.lay_is_checked;
        var pid = obj.data.pid;
        var menuId = obj.data.menuId;
        var ids = [];
        isChecked(d, pid, ids);
        Comm.treeGrid.setCheckStatus('treeTable', 'menuId', ids.join(","))
      })
    }
  }

  /*
      var menuIds = [];
      var d = Comm.treeGrid.checkStatus('treeTable'); //获取选中的数据
      if (d.data.length > 0) {
          for (var i = 0; i < d.data.length; i++) {
              menuIds.push(d.data[i].menuId)
          }
      }
      if (menuIds.length <= 0) {
          layer.msg("请选择菜单!", {
              icon: 5
          })
          return;
      }
      data.field.menuId = menuIds.join(',');

  */

  function isChecked(d, pid, ids) {
    if (pid > 0) {
      for (var i = 0; i < d.length; i++) {
        if (d[i].menuId == pid) {
          pid = d[i].pid;
          d[i].lay_is_checked = true;
          d[i].checkbox = true;
          ids.push(i);
        }
      }
      isChecked(d, pid, ids);
    } else {
      return;
    }
  }
</script>

</html>